package com.eve.eplus.common.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eve.eplus.R;
import com.eve.eplus.common.activity.StartActivity;
import com.eve.eplus.common.app.Constants;
import com.eve.eplus.common.app.SettingConstants;
import com.eve.eplus.common.task.ImageLoader;
import com.eve.eplus.common.tools.LogTools;
import com.eve.eplus.main.ImageViewActivity;
import com.eve.eplus.main.logic.SettingUtility;
import com.eve.eplus.sns.weibo.StatusesAPIDef;

/**
 * 主页内容适配器
 * 
 * @author Norsie
 * @create 12-12-20
 */
public class HomeContentAdapter extends BaseAdapter {

	private Context mContext;
	/**
	 * 微博内容，包括发布者、发布内容、转发数、评论数、附件（图片、视频、网址等，如果有）、被转发人（如果有）、被转发微博（如果有）、
	 * 被转发微博附件（如果有）
	 */
	private ArrayList<HashMap<String, String>> mStatus;

	private LayoutInflater mInflater;
	private Pattern urlPattern = Pattern
			.compile("http://t\\.cn/[A-Za-z0-9]+\\b"); // 微地址匹配
	private Matcher urlMatcher;
	private List<String> urlList;

	private boolean isScroll = false; // 是否正在滑动
	private ImageLoader mImageLoader;

	public HomeContentAdapter(Context context,
			ArrayList<HashMap<String, String>> status) {
		this.mStatus = status;
		this.mContext = context;
		mImageLoader = new ImageLoader(context);
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		if (mStatus == null)
			return 0;
		return mStatus.size();
	}

	public ImageLoader getImageLoader() {
		return mImageLoader;
	}

	public void refresh(ArrayList<HashMap<String, String>> list) {
		mStatus = list;
		notifyDataSetChanged();
	}

	public ArrayList<HashMap<String, String>> getData() {
		return mStatus;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mStatus.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub

		ViewHolder holder = null;
		if (convertView == null) {
			// 初始化控件
			convertView = mInflater.inflate(
					R.layout.activity_home_content_lvitem, null);
			holder = new ViewHolder();
			holder.profile = (ImageView) convertView
					.findViewById(R.id.iv_profile);
			holder.name = (TextView) convertView.findViewById(R.id.tv_name);
			holder.verified = (ImageView) convertView
					.findViewById(R.id.iv_verified);
			holder.comments_count = (TextView) convertView
					.findViewById(R.id.tv_comments_count);
			holder.reposts_count = (TextView) convertView
					.findViewById(R.id.tv_reposts_count);
			holder.text = (TextView) convertView.findViewById(R.id.tv_text);
			holder.thumbnail_pic = (ImageView) convertView
					.findViewById(R.id.iv_thumbnail_pic);
			holder.retweeted_text = (TextView) convertView
					.findViewById(R.id.tv_retweeted_text);
			holder.retweeted_thumbnail_pic = (ImageView) convertView
					.findViewById(R.id.iv_retweeted_thumbnail_pic);
			holder.created_at = (TextView) convertView
					.findViewById(R.id.tv_created_at);
			holder.source = (TextView) convertView.findViewById(R.id.tv_source);

			// 对设置项进行处理
			// 字体大小
			if (SettingUtility.getTextFontSizeSetting() == SettingConstants.TEXT_FONTSIZE_BIG) {
				holder.text.setTextSize(Constants.FONT_SIZE_BIG);
				holder.retweeted_text.setTextSize(Constants.FONT_SIZE_BIG);
			} else if (SettingUtility.getTextFontSizeSetting() == SettingConstants.TEXT_FONTSIZE_NORMAL) {
				holder.text.setTextSize(Constants.FONT_SIZE_NORMAL);
				holder.retweeted_text.setTextSize(Constants.FONT_SIZE_NORMAL);
			} else if (SettingUtility.getTextFontSizeSetting() == SettingConstants.TEXT_FONTSIZE_SMALL) {
				holder.text.setTextSize(Constants.FONT_SIZE_SMALL);
				holder.retweeted_text.setTextSize(Constants.FONT_SIZE_SMALL);
			}

			// 根据图片的大小改变显示样式
			if (SettingUtility.getImgLoadTypeSetting(true) == SettingConstants.IMG_LOADTYPE_BMIDDLE) {
				holder.thumbnail_pic.setScaleType(ScaleType.CENTER_CROP);
				holder.retweeted_thumbnail_pic
						.setScaleType(ScaleType.CENTER_CROP);
			} else if (SettingUtility.getImgLoadTypeSetting(true) == SettingConstants.IMG_LOADTYPE_THUMBNAIL) {
				holder.thumbnail_pic.setScaleType(ScaleType.FIT_START);
				holder.retweeted_thumbnail_pic
						.setScaleType(ScaleType.FIT_START);
			} else {
				holder.thumbnail_pic.setScaleType(ScaleType.FIT_START);
				holder.retweeted_thumbnail_pic
						.setScaleType(ScaleType.FIT_START);
			}

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		((ImageView) convertView.findViewById(R.id.iv_thumbnail_pic))
				.setVisibility(View.VISIBLE);
		((ImageView) convertView.findViewById(R.id.iv_retweeted_thumbnail_pic))
				.setVisibility(View.VISIBLE);
		((LinearLayout) convertView.findViewById(R.id.ll_retweeted))
				.setVisibility(View.VISIBLE);

		// 内容初始化
		holder.name.setText(null);
		holder.reposts_count.setText(null);
		holder.comments_count.setText(null);
		holder.created_at.setText(null);
		holder.source.setText(null);
		holder.text.setText(null);
		holder.profile.setImageDrawable(null);
		holder.retweeted_thumbnail_pic.setImageDrawable(null);
		holder.thumbnail_pic.setImageDrawable(null);
		holder.retweeted_text.setText(null);

		if (mStatus == null)
			return convertView;

		// 取值
		String profile = mStatus.get(position)
				.get(StatusesAPIDef.PROFILE_IMAGE_URL).toString();
		String name;
		if (mStatus.get(position).get(StatusesAPIDef.REMARK) != null) {
			name = mStatus.get(position).get(StatusesAPIDef.REMARK).toString()
					.length() > mStatus.get(position).get(StatusesAPIDef.NAME)
					.toString().length() ? mStatus.get(position)
					.get(StatusesAPIDef.REMARK).toString() : mStatus
					.get(position).get(StatusesAPIDef.NAME).toString();
		} else if (mStatus.get(position).containsKey(StatusesAPIDef.NAME))
			name = mStatus.get(position).get(StatusesAPIDef.NAME).toString();
		else
			name = "";

		String reposts_count = mStatus.get(position)
				.get(StatusesAPIDef.REPOSTS_COUNT).toString();
		String comments_count = mStatus.get(position)
				.get(StatusesAPIDef.COMMENTS_COUNT).toString();
		String text = mStatus.get(position).get(StatusesAPIDef.TEXT).toString();
		String created_at = mStatus.get(position)
				.get(StatusesAPIDef.CREATED_AT).toString();
		String source = mStatus.get(position).get(StatusesAPIDef.SOURCE)
				.toString();
		String verified = mStatus.get(position).get(StatusesAPIDef.VERIFIED)
				.toString();

		String retweeted_name = null;
		String retweeted_text = null;

		String thumbnail_pic = null;
		String retweeted_thumbnail_pic = null;
		if (mStatus.get(position).get(StatusesAPIDef.PIC) != null)
			thumbnail_pic = mStatus.get(position).get(StatusesAPIDef.PIC)
					.toString();

		// 内容填充
		holder.name.setText(name);
		holder.reposts_count.setText(reposts_count);
		holder.comments_count.setText(comments_count);
		holder.created_at.setText(created_at);
		holder.source.setText(Html.fromHtml(source) + "");
		holder.text.setText("");

		if (verified.equals("true"))
			holder.verified.setVisibility(View.VISIBLE);
		else
			holder.verified.setVisibility(View.INVISIBLE);

		// 对微博内容中的网址信息进行处理并赋值
		urlHandle(stringFilter(text), holder.text);

		// 图片的处理
		// 头像
		if (profile != null) {
			if (!isScroll) {
				mImageLoader.DisplayImage(profile, holder.profile, false);
			} else {
				mImageLoader.DisplayImage(profile, holder.profile, true);
			}
		}
		// 判断是否含有转发微博,并进行相应处理
		if (mStatus.get(position).get(StatusesAPIDef.RETWEETED_NAME) == null
				&& mStatus.get(position).get(StatusesAPIDef.RETWEETED_TEXT) == null
				|| mStatus.get(position).get(StatusesAPIDef.RETWEETED_NAME)
						.equals("")
				&& mStatus.get(position).get(StatusesAPIDef.RETWEETED_TEXT)
						.equals("")) {
			// 不含有转发微博
			// 隐藏转发部分内容
			((LinearLayout) convertView.findViewById(R.id.ll_retweeted))
					.setVisibility(View.GONE);

			// 原文图片的处理
			if (thumbnail_pic != null) {
				if (!isScroll) {
					mImageLoader.DisplayImage(thumbnail_pic,
							holder.thumbnail_pic, false);
				} else {
					mImageLoader.DisplayImage(thumbnail_pic,
							holder.thumbnail_pic, true);
				}
			} else
				((ImageView) convertView.findViewById(R.id.iv_thumbnail_pic))
						.setVisibility(View.GONE);

		} else {
			// 含有转发微博
			// 显示转发部分，隐藏原文图片区域
			((LinearLayout) convertView.findViewById(R.id.ll_retweeted))
					.setVisibility(View.VISIBLE);
			((ImageView) convertView.findViewById(R.id.iv_thumbnail_pic))
					.setVisibility(View.GONE);

			if (mStatus.get(position).get(StatusesAPIDef.RETWEETED_PIC) != null)
				retweeted_thumbnail_pic = mStatus.get(position)
						.get(StatusesAPIDef.RETWEETED_PIC).toString();

			retweeted_name = mStatus.get(position)
					.get(StatusesAPIDef.RETWEETED_NAME).toString();
			retweeted_text = mStatus.get(position)
					.get(StatusesAPIDef.RETWEETED_TEXT).toString();
			// holder.retweeted_name.setText(retweeted_name);
			holder.retweeted_text.setText("");
			// 对微博内容中的网址信息进行处理并赋值
			urlHandle(stringFilter(retweeted_name +":"+ retweeted_text),
					holder.retweeted_text);

			// 转发图片的处理
			if (retweeted_thumbnail_pic != null) {
				if (!isScroll) {
					mImageLoader.DisplayImage(retweeted_thumbnail_pic,
							holder.retweeted_thumbnail_pic, false);
				} else {
					mImageLoader.DisplayImage(retweeted_thumbnail_pic,
							holder.retweeted_thumbnail_pic, true);
				}
			} else
				((ImageView) convertView
						.findViewById(R.id.iv_retweeted_thumbnail_pic))
						.setVisibility(View.GONE);
		}
		holder.thumbnail_pic.setTag(position);
		holder.thumbnail_pic.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, ImageViewActivity.class);
				intent.putExtra(Constants.HOME_CONTENT,
						mStatus.get((Integer) v.getTag()));
				mContext.startActivity(intent);
			}
		});

		holder.retweeted_thumbnail_pic.setTag(position);
		holder.retweeted_thumbnail_pic
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(mContext,
								ImageViewActivity.class);
						intent.putExtra(Constants.HOME_CONTENT,
								mStatus.get((Integer) v.getTag()));
						mContext.startActivity(intent);
					}
				});

		return convertView;
	}

	static class ViewHolder {
		ImageView profile; // 头像
		TextView name; // 发布者
		ImageView verified; // 认证
		TextView comments_count; // 评论数
		TextView reposts_count; // 转发数
		TextView text; // 微薄内容
		ImageView thumbnail_pic; // 图片
		TextView retweeted_text; // 转发的内容
		ImageView retweeted_thumbnail_pic; // 转发的图片
		TextView created_at; // 创建时间
		TextView source; // 微博来源
	}

	public void setScrollState(boolean isScrolling) {
		this.isScroll = isScrolling;
	}

	/**
	 * url處理
	 * */
	private void urlHandle(String text, TextView tv) {
		urlList = new ArrayList<String>();
		urlMatcher = urlPattern.matcher(text);
		StringBuffer sb = new StringBuffer();
		while (urlMatcher.find()) {
			urlMatcher.appendReplacement(sb, ""); // 查詢第一處匹配內容，將其刪除，然後將此之前的內容保存在sb中
			urlList.add(urlMatcher.group()); // 将匹配的内容添加到列表里

			tv.append(sb); // 將處理好的文職寫到textview中

			// 插入图片
			// tv.append(Html.fromHtml(
			// "<img src='" + R.drawable.icon_link + "'/>", imageGetter,
			// // null)); // 在匹配內容處插入圖片

			// 文字背景颜色
			// SpannableStringBuilder style=new
			// SpannableStringBuilder(Html.fromHtml("<font color=\"#45cef6\">[网址]</font>"));
			// style.setSpan(new BackgroundColorSpan(
			// mContext.getResources().getColor(R.color.gray_color_a)),0,4,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			// tv.append(style);

			// 插入文字
			tv.append(Html.fromHtml("<font color=\"#45cef6\">[网址]</font>"));
			sb.setLength(0); // 清空sb內容
			urlMatcher.appendTail(sb); // 將未匹配的內容放入sb
			urlMatcher = urlPattern.matcher(sb); // 重新設置Pattern，以新的sb的內容進行查詢
			sb.setLength(0); // 清空sb以備後用

		}
		sb.setLength(0);
		urlMatcher.appendTail(sb);
		tv.append(sb);
	}

	// TextView中的图片处理
	ImageGetter imageGetter = new ImageGetter() {
		@Override
		public Drawable getDrawable(String source) {
			int id = Integer.parseInt(source);
			// 根据id从资源文件中获取图片对象
			Drawable drawable = mContext.getResources().getDrawable(id);
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
					drawable.getIntrinsicHeight());
			return drawable;
		}
	};

	/**
	 * 半角转换为全角,去除特殊字符或将所有中文标号替换为英文标号
	 * 
	 * @param str
	 * @return
	 */
	public static String stringFilter(String str) {
		if (str.length() > 0) {
			char[] c = str.toCharArray();
			for (int i = 0; i < c.length; i++) {
				if (c[i] == 12288) {
					c[i] = (char) 32;
					continue;
				}
				if (c[i] > 65280 && c[i] < 65375)
					c[i] = (char) (c[i] - 65248);
			}
			str = new String(c);
			str = str.replaceAll("【", "[").replaceAll("】", "]")
					.replaceAll("！", "!").replaceAll("：", ":"); // 替换中文标号
			String regEx = ""; // "[『』]"; // 清除掉特殊字符
			Pattern p = Pattern.compile(regEx);
			Matcher m = p.matcher(str);
			return m.replaceAll("").trim();
		} else
			return str;
	}

}
